package com.link.base.base.orgnization.service;

import com.link.base.base.orgnization.dao.mybatis.mapper.PartnerMapper;
import com.link.base.base.orgnization.model.Partner;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.cllog.LCLogger;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;


@Service
public class PartnerServiceImpl extends BasicServiceImpl<Partner> implements PartnerService {

    @Resource
    private PartnerMapper partnerMapper;

    @Override
    public BasicMapper<Partner> getBasicMapper() {
        return partnerMapper;
    }

    @Override
    public void beforUpsert(Partner record) {
        record.setRecordType("LoyaltyPartner");
    }



    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void defaultPartnerUpdate(Partner partner) throws Exception {
        Partner partnerParam = new Partner();
        partnerParam.setDefaultFlag("Y");
        partnerParam.setPageFlag(false);
        QueryParams qps = new QueryParams();
        qps.setPageFlag(false);
        qps.addFilter(new Filter("defaultFlag", Filter.OP_EQUAL, "Y"));
        partnerParam = (Partner) BasicModel.transformClass(partnerParam, qps);
        List<Partner> partnerList = partnerMapper.queryByExamplePage(partnerParam);
        if (CollectionUtils.isEmpty(partnerList)) {
            partnerMapper.defaultPartnerUpdate(partner);
        } else {
            partnerList.forEach(f -> {
                f.setDefaultFlag("N");
                try {
                    partnerMapper.defaultPartnerUpdate(f);
                } catch (Exception e) {
                    LCLogger.withException(e);
                }
            });
            if (StringUtils.isBlank(partner.getDefaultFlag())) {
                partner.setDefaultFlag("Y");
            }
            partnerMapper.defaultPartnerUpdate(partner);
        }
    }
}
